<template>
  <div>
    <el-header class="navbar">
      <div class="navbar-left">
        <img src="http://cdn.qiniu.liyansheng.top/img/sport_icon_154800.png" alt="Logo" class="logo">
        <span class="brand">体质检测管理</span>
        <!-- 菜单 -->
        <el-menu mode="horizontal" :default-active="defaultActive" @select="handleSelect">
          <el-menu-item v-for="menu in menus" :index="menu.key" :key="menu.key">
            {{ menu.title }}
          </el-menu-item>
        </el-menu>
      </div>
      <div class="navbar-right">
        <el-dropdown v-if="currentUser">
          <span class="el-dropdown-link">
            <img
              :src="currentUser.avatar || 'http://cdn.qiniu.liyansheng.top/img/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240826190120.jpg'"
              alt="头像" class="avatar"> {{ currentUser.username }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="toInfo">个人中心</el-dropdown-item>
            <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button v-else type="primary" @click="goToLogin">登录</el-button>
      </div>
    </el-header>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'HomePage',
  computed: {
    currentUser() {
      return this.$store.getters.currentUser;
    },
    menus() {
      return this.$store.getters.userMenus;
    },
    defaultActive() {
      return 'index'; // 默认选中的菜单项
    }
  },
  methods: {
    handleSelect(key) {
      const selectedMenu = this.menus.find(menu => menu.key === key);
      if (selectedMenu) {
        this.$router.push(selectedMenu.route);
      }
    },
    toInfo(){
      this.$router.push('/info');
    },
    goToLogin() {
      this.$router.push('/login');
    },
    testClick() {
      console.log('Test click');
    },
    logout() {
      this.$store.dispatch('logout')
        .then(() => {
          this.$router.push('/login');
        })
        .catch(error => {
          console.error('Logout failed:', error);
        });
    }

  }
};
</script>

<style scoped>
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 60px;
  background-color: #333;
  color: #fff;
  padding: 0 20px;
  position: fixed;
  top: 0;
  z-index: 1000;
}

.navbar-left {
  display: flex;
  align-items: center;
}

.logo {
  height: 40px;
  margin-right: 10px;
}

.brand {
  font-size: 30px;
  font-weight: bold;
  margin-right: 30px;
}

.el-menu {
  background-color: transparent;
  color: #fff;
}

.el-menu-item:hover,
.el-menu-item.is-active {
  background-color: #555;
}

.navbar-right {
  display: flex;
  align-items: center;
}

.avatar {
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}
</style>